package util

import (
	"common/helper"
	"errors"
	"github.com/valyala/fasthttp"
	"strconv"
)

type PageParams struct {
	PageSize    uint32 `json:"pageSize"`
	CurrentPage uint32 `json:"currentPage"`
	Total       uint32 `json:"total"`
}

type Controller interface {
	Execution(ctx *fasthttp.RequestCtx, entity interface{}, f func(entity *interface{}) error)
	ExecutionGetId(ctx *fasthttp.RequestCtx, f func(id uint32) error)
}

type ControllerImpl struct {
}

func (b *ControllerImpl) Execution(ctx *fasthttp.RequestCtx, f func(e []byte) error) {
	err := func(ctx *fasthttp.RequestCtx) error {
		data := ctx.PostBody()
		if data == nil {
			return errors.New(helper.ParamErr)
		}
		return f(data)
	}(ctx)
	if err != nil {
		helper.Print(ctx, false, err.Error())
	}
}
func (b *ControllerImpl) ExecutionGetId(ctx *fasthttp.RequestCtx, f func(id uint32) error) {
	if err := func(ctx *fasthttp.RequestCtx) error {
		id, _ := strconv.Atoi(string(ctx.QueryArgs().Peek("id")))
		if id == 0 {
			return errors.New(helper.ParamErr)
		}
		return f(uint32(id))
	}(ctx); err != nil {
		helper.Print(ctx, false, err.Error())
	}
}
